/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.setupwizard;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.privacy.PrivacyGroupSetupListActivity;
import com.phonebooksharing.android.provider.PhonebookSharing.Settings;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.ProfileItem;
import com.phonebooksharing.dto.ReturnItem;

public class SetupWizard2 extends Activity {
	
	private String phone, sim;
	private EditText user, pwd, conPwd;
	
	@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.wiz2);
        
        final TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        phone = tm.getLine1Number();
        sim   = tm.getSimSerialNumber();
        
        if(TextUtils.isEmpty(phone)) {
        	phone = "(Unknown)";
        }
        
        ((TextView)findViewById(R.id.text4)).setText(phone);
        
        user = (EditText)findViewById(R.id.text1);
        pwd = (EditText)findViewById(R.id.text2);
        conPwd = (EditText)findViewById(R.id.text3);
        
        ((Button)findViewById(android.R.id.button1)).setVisibility(View.INVISIBLE);
        
        Button next = (Button)findViewById(android.R.id.button2);
        next.setText("Next");
        next.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.next, 0);
        next.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(checkData()) {
					new CheckAccountTask().execute();
				}
			}
		});
	}
	
	class ForgotPasswordTask extends NetworkHandlerTask<Void, ReturnItem, Void> {
		private ProgressDialog d;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			d = new ProgressDialog(SetupWizard2.this);
	        d.setTitle("Please wait");
	        d.setMessage("Requesting forgot password mail to be sent...");
	        d.setIndeterminate(true);
	        d.setCancelable(true);
	        d.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				final String url = String.format(Global.PROFILE_SERVLET_URL, "l" /*ac*/, "" /*q*/);//action validate
				final ProfileItem pi = new ProfileItem();
				pi.username = user.getText().toString();
				pi.password = pwd.getText().toString();//TODO: encrypt password before sending
				pi.phone = phone;
				pi.sim = sim;

				publishProgress((ReturnItem)doNetworkPost(url, pi));
				return null;
	        } catch (Exception e) {
	        	//TODO: toast something here
	            e.printStackTrace();
	        }
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(ReturnItem... values) {
			super.onProgressUpdate(values);
			final ReturnItem ri = values[0];
			
			if(ri.isOK()) {
				Toast.makeText(SetupWizard2.this, "You'll be receiving an email soon with your credentials!", Toast.LENGTH_LONG).show();
			} else {//if NOK
				Toast.makeText(SetupWizard2.this, "Could not request password to be send! Please contact suport. ErrCode [" + ri.getErrorCode() + "]", Toast.LENGTH_LONG).show(); 
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			d.dismiss();
		}
	}
	
	class CheckAccountTask extends NetworkHandlerTask<Void, ReturnItem, Void> {
		private ProgressDialog d;
		private boolean isForgot;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			d = new ProgressDialog(SetupWizard2.this);
	        d.setTitle("Please wait");
	        d.setMessage("We are now validating your profile...");
	        d.setIndeterminate(true);
	        d.setCancelable(true);
	        d.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				final String url = String.format(Global.PROFILE_SERVLET_URL, "v" /*ac*/, "" /*q*/);//action validate
				final ProfileItem pi = new ProfileItem();
				pi.username = user.getText().toString();
				pi.password = pwd.getText().toString();//TODO: encrypt password before sending
				pi.phone = phone;
				pi.sim = sim;

				publishProgress((ReturnItem)doNetworkPost(url, pi));
				return null;
	        } catch (Exception e) {
	        	//TODO: toast something here
	            e.printStackTrace();
	        }
			return null;
		}
		
		@Override
		protected void onProgressUpdate(ReturnItem... values) {
			super.onProgressUpdate(values);
			final ReturnItem ri = values[0];
			
			if(!ri.isOK()) {
				int errCode = ri.getErrorCode();
				if(errCode == ProfileItem.PROFILE_EXISTS) {
					new AlertDialog.Builder(SetupWizard2.this)
	                .setIcon(android.R.drawable.ic_dialog_alert)
	                .setTitle("Profile found")
	                .setMessage("A profile with this username has been found in our records but the password does not match.\nWould you like to:")
	                .setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                        /* User clicked OK so do some stuff */
	                    }
	                })
	                .setNegativeButton("Forgot Password", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	isForgot = true; //schedule to open new popup when this one ends
	                    }
	                })
	                .create().show();
				} else {
					//TODO: what??
				}
			} else {//if ok
				final ContentValues cv = new ContentValues();
				cv.put(Settings.AUTH_ID, ri.getAuthItem());
				ContentResolver cr = getContentResolver();
				cr.delete(Settings.CONTENT_URI, null, null);
				cr.insert(Settings.CONTENT_URI, cv);
				
				Global.loadConfig(getApplicationContext());
				
				//FIXME:  if ok, should send a msg from server saying that is new or old profile.
//				Toast.makeText(SetupWizard2.this, "We've retrieved your data, you don't need to setup again!\n\nPlease access your Phonebook Sharing again.", Toast.LENGTH_LONG).show();
				
				//if the profile is ok, we should only update the new authItem
				//send a message to the user and close the system.
//				finish();
				
				//now config groups
				Intent i = new Intent(SetupWizard2.this, PrivacyGroupSetupListActivity.class);
				i.putExtra(PrivacyGroupSetupListActivity.IS_INITIAL_SETUP, true);
				startActivity(i);
				finish();
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			d.dismiss();
			
			if(isForgot) {
				new ForgotPasswordTask().execute();
			}
		}
	}
	
	protected boolean checkData() {
		final String u = user.getText().toString();
		final String p = pwd.getText().toString();
		final String cp = conPwd.getText().toString();
		
		if(!u.contains("@") || !u.contains(".")) {
			user.setError("Invalid Username! Is this a valid email?");
			return false;
		}
		
		if(p.length() < 5) {
			pwd.setError("Password must be at least 5 chars!");
			return false;
		}
		
		if(!p.equals(cp)) {
			conPwd.setError("Password does not match!");
			return false;
		}
		
		return true;
	}
}
